package cmd

import (
	"context"
	"fmt"
	"github.com/spf13/cobra"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"strconv"
	"time"
)

// deployment名称
var deploymentGetName string

func init() {
	// 获取 Deployment 的选项参数
	deploymentGetCmd.Flags().StringVar(&deploymentGetName, "name", "", "deployment name")
}

// Deployment 命令
var deploymentRootCmd = cobra.Command{
	Use:     "deployment",
	Aliases: []string{"deploy"},
	Short:   "deployment is used to manage kubernetes Deployments",
}

// Deployment Get 命令
var deploymentGetCmd = cobra.Command{
	Use:   "get",
	Short: "get deployment or deployment list",
	Run: func(cmd *cobra.Command, args []string) {
		if namespace == "" {
			cmd.Help()
			return
		}

		// 创建 Kubernetes 客户端对象
		k8sClient, err := createK8SClient()
		if err != nil {
			fmt.Println("Err:", err)
			return
		}

		// 根据 deploymentGetName 参数是否为空来决定显示单个 Deployment 信息还是所有 Deployment 信息
		listOption := metav1.ListOptions{}
		// 如果指定了 Deployment Name，那么只获取单个 Deployment 的信息
		if deploymentGetName != "" {
			listOption.FieldSelector = fmt.Sprintf("metadata.name=%s", deploymentGetName)
		}

		// 调用 List 接口获取 Deployment 列表
		// deploymentList, err := k8sClient.ExtensionsV1beta1().Deployments(namespace).List(context.Background(),listOption)
		deploymentList, err := k8sClient.AppsV1().Deployments(namespace).List(context.Background(), listOption)
		if err != nil {
			fmt.Println("Err:", err)
			return
		}

		// 遍历 Deployment List，显示 Deployment 信息
		printFmt := "%-10s\t%-10s\t%-10s\t%-10s\t%-10s\t%-10s\n"
		fmt.Printf(printFmt, "NAME", "DESIRED", "CURRENT", "UP-TO-DATE", "AVAILABLE", "AGE")
		for _, deployment := range deploymentList.Items {
			fmt.Printf(printFmt, deployment.Name, strconv.Itoa(int(*deployment.Spec.Replicas)), strconv.Itoa(int(deployment.Status.Replicas)),
				strconv.Itoa(int(deployment.Status.UpdatedReplicas)), strconv.Itoa(int(deployment.Status.AvailableReplicas)),
				time.Now().Sub(deployment.GetCreationTimestamp().Time))
		}
	},
}
